package org.linlinjava.litemall.admin.web.order_manage;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.linlinjava.litemall.admin.constant.LoginType;
import org.linlinjava.litemall.admin.constant.PhoneCode;
import org.linlinjava.litemall.admin.enums.AdminErrorCode;
import org.linlinjava.litemall.admin.service.order_manage.AgedmallAuthService;
import org.linlinjava.litemall.admin.shiro.ThirdPartyTypeToken;
import org.linlinjava.litemall.admin.vo.auth.BindingPhoneWechatVo;
import org.linlinjava.litemall.admin.vo.auth.PhoneLoginVo;
import org.linlinjava.litemall.admin.vo.auth.UploadPassword;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.service.AgedmallExpressService;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.ADMIN_INVALID_ACCOUNT;

/**
 * @author wj
 * @date 2021/8/4 16:55
 */
@RestController
@RequestMapping("/auth")
public class AgedMallAuthController {

    @Resource
    private LitemallAdminService litemallAdminService;

    @Resource
    private AgedmallAuthService agedmallAuthService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AgedmallExpressService agedmallExpressService;

    /**
     * 密码登录接口
     * @return
     */
    @PostMapping("/login")
    public Object adminLogin(@RequestBody  PhoneLoginVo phoneLoginVo){

        Subject currentUser = SecurityUtils.getSubject();
        try {
            if(LoginType.WECHAT_LOGIN.equals(phoneLoginVo.getLoginType())){
                currentUser.login(new ThirdPartyTypeToken(phoneLoginVo.getPhone()));
            }
            else{
                currentUser.login(new ThirdPartyTypeToken(phoneLoginVo.getPhone(), phoneLoginVo.getPassword()));
            }
        } catch (UnknownAccountException uae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确");
        } catch (LockedAccountException lae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");

        } catch (AuthenticationException ae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "认证失败");
        }

        currentUser = SecurityUtils.getSubject();
        LitemallAdmin admin = (LitemallAdmin) currentUser.getPrincipal();
        admin.setLastLoginTime(LocalDateTime.now());
        litemallAdminService.updateById(admin);
        // userInfo
        Map<String, Object> adminInfo = new HashMap<String, Object>();
        adminInfo.put("id", admin.getId());
        adminInfo.put("nickName", admin.getUsername());
        adminInfo.put("avatar", admin.getAvatar());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", currentUser.getSession().getId());
        result.put("adminInfo", adminInfo);
        return ResponseUtil.ok(result);
    }


    /**
     * 获取验证码
     * @return
     */
    @PostMapping("/binding_code/{phone}/{type}/{isVoice}")
    public Object bindingCode(@PathVariable String phone,@PathVariable Integer type,@PathVariable Integer isVoice){
        return agedmallAuthService.bindingCode(phone,type,isVoice);
    }

    /**
     * 绑定手机号码和微信
     * @return
     */
    @PostMapping("/binding_phone_wechat")
    public Object bindingPhoneWechat(@RequestBody BindingPhoneWechatVo bindingPhoneWechatVo){
        String redisCode=stringRedisTemplate.opsForValue().get(PhoneCode.BINDING_PHONE+bindingPhoneWechatVo.getPhone());
        if(StringUtils.isBlank(redisCode)){
            return ResponseUtil.fail(AdminErrorCode.PLEASE_SEND_PHONE_CODE.getCode(),AdminErrorCode.PLEASE_SEND_PHONE_CODE.getMessage());
        }
        if(StringUtils.isBlank(bindingPhoneWechatVo.getCode())){
            return ResponseUtil.fail(AdminErrorCode.PHONE_CODE_NOT_NULL.getCode(),AdminErrorCode.PHONE_CODE_NOT_NULL.getMessage());
        }
        if(!redisCode.equals(bindingPhoneWechatVo.getCode())){
            return ResponseUtil.fail(AdminErrorCode.PHONE_CODE_NOT_MATCH.getCode(),AdminErrorCode.PHONE_CODE_NOT_MATCH.getMessage());
        }
        if(StringUtils.isBlank(bindingPhoneWechatVo.getPassword())){
            return ResponseUtil.fail(AdminErrorCode.PASSWORD_NOT_NULL.getCode(),AdminErrorCode.PASSWORD_NOT_NULL.getMessage());
        }
        //正常
//         return adminLogin(new PhoneLoginVo(bindingPhoneWechatVo.getPhone(),"",LoginType.WECHAT_LOGIN));
        return agedmallAuthService.bindingPhoneWechat(bindingPhoneWechatVo);
    }


    /**
     * 获取省市区列表
     * @return
     */
    @GetMapping("/getCityList")
    public Object getCityList(){
        return agedmallAuthService.getCityList();
    }


    /**
     * 获取省市列表-树状结构
     */
    @GetMapping("/getTwoLevelCityList")
    public Object  getTwoLevelCityList(){
       return agedmallAuthService.twoLevelCityList();
    }

    /**
     * 修改密码
     * @return
     */
    @PostMapping("/updatePassword")
    public Object updatePassword(@RequestBody UploadPassword uploadPassword){
        String redisCode=stringRedisTemplate.opsForValue().get(PhoneCode.CHANGE_PHONE_PASSWORD+uploadPassword.getPhone());
        if(StringUtils.isBlank(redisCode)){
            return ResponseUtil.fail(AdminErrorCode.PLEASE_SEND_PHONE_CODE.getCode(),AdminErrorCode.PLEASE_SEND_PHONE_CODE.getMessage());
        }
        if(StringUtils.isBlank(uploadPassword.getCode())){
            return ResponseUtil.fail(AdminErrorCode.PHONE_CODE_NOT_NULL.getCode(),AdminErrorCode.PHONE_CODE_NOT_NULL.getMessage());
        }
        if(!redisCode.equals(uploadPassword.getCode())){
            return ResponseUtil.fail(AdminErrorCode.PHONE_CODE_NOT_MATCH.getCode(),AdminErrorCode.PHONE_CODE_NOT_MATCH.getMessage());
        }
        if(StringUtils.isBlank(uploadPassword.getPassword())){
            return ResponseUtil.fail(AdminErrorCode.PASSWORD_NOT_NULL.getCode(),AdminErrorCode.PASSWORD_NOT_NULL.getMessage());
        }

        return agedmallAuthService.updatePassword(uploadPassword);
    }


    @RequestMapping("/401")
    public Object page401() {
        return ResponseUtil.unlogin();
    }


//    @Resource
//    private DirectExchangeProducer directExchangeProducer;
//
//    @RequestMapping("/test")
//    public String test(){
//        directExchangeProducer.send("这是测试消息11111", DirectExchangeRabbitMQConfig.TO_WECHAT_NOTICE);
//        return "ok";
//    }

    @RequestMapping("/getExpressList")
    public Object getExpressList() {
        return agedmallExpressService.list();
    }
}
